<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" title="加入俱乐部" />
      <scroll-view scroll-y class="scroll-view-content">
        <view class="form-container">
          <!-- 俱乐部logo -->
          <view class="form-item">
            <text class="form-label">俱乐部logo <text class="required">*</text></text>
            <text class="form-hint">(400px * 400px)</text>
            <view class="upload-box" @click="uploadLogo">
              <image
                v-if="formData.logo"
                :src="formData.logo"
                class="uploaded-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <image :src="imgUrl + 'upload-icon.png'" class="upload-icon" />
                <text class="upload-text">点击上传</text>
              </view>
            </view>
          </view>

          <!-- 俱乐部名称 -->
          <view class="form-item">
            <text class="form-label">俱乐部名称 <text class="required">*</text></text>
            <input v-model="formData.name" class="form-input" placeholder="请输入" maxlength="50" />
          </view>

          <!-- 联系人 -->
          <view class="form-item">
            <text class="form-label">联系人 <text class="required">*</text></text>
            <input
              v-model="formData.contacts_name"
              class="form-input"
              placeholder="请输入"
              maxlength="20"
            />
          </view>

          <!-- 联系电话 -->
          <view class="form-item">
            <text class="form-label">联系电话 <text class="required">*</text></text>
            <input
              v-model="formData.contacts_mobile"
              class="form-input"
              placeholder="请输入"
              type="number"
              maxlength="11"
            />
          </view>

          <!-- 创建者 -->
          <view class="form-item">
            <text class="form-label">创建者</text>
            <view class="form-readonly">{{ formData.creator_name || '未设置' }}</view>
          </view>

          <!-- 领队人 -->
          <view class="form-item">
            <text class="form-label">领队人</text>
            <input
              v-model="formData.leader_name"
              class="form-input"
              placeholder="请输入"
              maxlength="20"
            />
          </view>

          <!-- 地址 -->
          <view class="form-item">
            <text class="form-label">地址</text>
            <input
              v-model="formData.address"
              class="form-input"
              placeholder="请输入详细地址"
              maxlength="100"
            />
          </view>

          <!-- 所在城市 -->
          <view class="form-item">
            <text class="form-label">所在城市 <text class="required">*</text></text>
            <area-picker
              ref="areaPickerRef"
              :placeholder="'请选择省市区'"
              :arrow-icon="imgUrl + 'arrow-right.png'"
              :default-value="{
                province: formData.province_id,
                city: formData.city_id,
                district: formData.region_id
              }"
              @change="onAreaChange"
              @cancel="onAreaCancel"
            />
            <!-- 显示已选择的城市信息 -->
            <view v-if="formData.city" class="selected-city-info">
              <text class="city-text">已选择：{{ formData.city }}</text>
              <text class="city-reset" @click="resetAreaSelection">重新选择</text>
            </view>
          </view>

          <!-- 执照号码 -->
          <view class="form-item">
            <text class="form-label">执照号码</text>
            <input
              v-model="formData.license"
              class="form-input"
              placeholder="请输入"
              maxlength="50"
            />
          </view>

          <!-- 营业执照 -->
          <view class="form-item">
            <text class="form-label">营业执照 盖章后上传</text>
            <view class="upload-box" @click="uploadBusiness">
              <image
                v-if="formData.business"
                :src="formData.business"
                class="uploaded-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <image :src="imgUrl + 'upload-icon.png'" class="upload-icon" />
                <text class="upload-text">点击上传</text>
              </view>
            </view>
          </view>

          <!-- 入驻申请函 -->
          <view class="form-item">
            <text class="form-label">入驻申请函 下载盖章后拍照上传</text>
            <view class="download-section">
              <text class="download-link" @click="downloadApplication">下载附件</text>
            </view>
            <view class="upload-box" @click="uploadApply">
              <image
                v-if="formData.apply"
                :src="formData.apply"
                class="uploaded-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <image :src="imgUrl + 'upload-icon.png'" class="upload-icon" />
                <text class="upload-text">点击上传</text>
              </view>
            </view>
          </view>

          <!-- 俱乐部简介 -->
          <view class="form-item">
            <text class="form-label">俱乐部简介</text>
            <textarea
              v-model="formData.desc"
              class="form-textarea"
              placeholder="请输入"
              maxlength="500"
              auto-height
            />
          </view>
        </view>
      </scroll-view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button class="submit-btn" @click="submitForm" :disabled="!isFormValid"> 确认提交 </button>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
  import { ref, computed, reactive } from 'vue'
  import { useOutsideAppStore } from '@/store/app'
  import { imgUrl } from '@/utils/config'
  import { onShow } from '@dcloudio/uni-app'
  import { useRequest } from '@/api'
  import AreaPicker from '@/components/AreaPicker/index.vue'
  const { API_MEMBER_ADDCLUB_POST } = useRequest()
  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)

  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }

  // 用户信息
  const userInfo = ref({
    nickname: '',
    username: ''
  })
  // 表单数据
  const formData = reactive({
    logo: '', // 图标
    name: '', // 机构名称
    contacts_name: '', // 联系人姓名
    contacts_mobile: '', // 联系电话
    address: '', // 地址
    creator_name: '', // 创建者
    leader_name: '', // 领队人
    license: '', // 执照号码
    business: '', // 营业执照
    apply: '', // 入驻申请函
    desc: '', // 简介
    city: '', // 城市显示文本
    province_id: '', // 省份ID
    city_id: '', // 城市ID
    region_id: '' // 区/县ID
  })

  // 表单验证
  const isFormValid = computed(() => {
    return (
      formData.logo &&
      formData.name &&
      formData.contacts_name &&
      formData.contacts_mobile &&
      formData.city &&
      formData.province_id &&
      formData.city_id &&
      formData.region_id
    )
  })

  // 上传logo
  const uploadLogo = () => {
    // 检查是否已登录
    const token = uni.getStorageSync('token')
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }

    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const filePath = res.tempFilePaths[0]
        try {
          uni.showLoading({ title: '上传中...' })

          // 使用 uni.uploadFile 进行文件上传
          const uploadRes = await new Promise((resolve, reject) => {
            uni.uploadFile({
              url: `${import.meta.env.VITE_APP_API_BASEURL}/api/index/upload`,
              filePath: filePath,
              name: 'file',
              header: {
                Authorization: token
              },
              success: (uploadRes) => {
                try {
                  const data = JSON.parse(uploadRes.data)
                  resolve(data)
                } catch (e) {
                  resolve(uploadRes)
                }
              },
              fail: (error) => {
                reject(error)
              }
            })
          })

          console.log('logo上传结果:', uploadRes)

          // 期望后端返回 { code:1, data: { url: 'xxx' } }
          if (uploadRes && uploadRes.code === 1) {
            const url = uploadRes.data?.fullurl
            formData.logo = url
            uni.showToast({ title: '上传成功', icon: 'success' })
          } else {
            uni.showToast({ title: uploadRes.msg || '上传失败', icon: 'none' })
          }
        } catch (err) {
          console.error('logo上传失败:', err)
          uni.showToast({ title: '上传失败', icon: 'none' })
        } finally {
          uni.hideLoading()
        }
      }
    })
  }

  // 上传营业执照
  const uploadBusiness = () => {
    // 检查是否已登录
    const token = uni.getStorageSync('token')
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }

    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const filePath = res.tempFilePaths[0]
        try {
          uni.showLoading({ title: '上传中...' })

          // 使用 uni.uploadFile 进行文件上传
          const uploadRes = await new Promise((resolve, reject) => {
            uni.uploadFile({
              url: `${import.meta.env.VITE_APP_API_BASEURL}/api/index/upload`,
              filePath: filePath,
              name: 'file',
              header: {
                Authorization: token
              },
              success: (uploadRes) => {
                try {
                  const data = JSON.parse(uploadRes.data)
                  resolve(data)
                } catch (e) {
                  resolve(uploadRes)
                }
              },
              fail: (error) => {
                reject(error)
              }
            })
          })

          console.log('营业执照上传结果:', uploadRes)

          // 期望后端返回 { code:1, data: { url: 'xxx' } }
          if (uploadRes && uploadRes.code === 1) {
            const url = uploadRes.data?.fullurl
            formData.business = url
            uni.showToast({ title: '上传成功', icon: 'success' })
          } else {
            uni.showToast({ title: uploadRes.msg || '上传失败', icon: 'none' })
          }
        } catch (err) {
          console.error('营业执照上传失败:', err)
          uni.showToast({ title: '上传失败', icon: 'none' })
        } finally {
          uni.hideLoading()
        }
      }
    })
  }

  // 上传申请函
  const uploadApply = () => {
    // 检查是否已登录
    const token = uni.getStorageSync('token')
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }

    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const filePath = res.tempFilePaths[0]
        try {
          uni.showLoading({ title: '上传中...' })

          // 使用 uni.uploadFile 进行文件上传
          const uploadRes = await new Promise((resolve, reject) => {
            uni.uploadFile({
              url: `${import.meta.env.VITE_APP_API_BASEURL}/api/index/upload`,
              filePath: filePath,
              name: 'file',
              header: {
                Authorization: token
              },
              success: (uploadRes) => {
                try {
                  const data = JSON.parse(uploadRes.data)
                  resolve(data)
                } catch (e) {
                  resolve(uploadRes)
                }
              },
              fail: (error) => {
                reject(error)
              }
            })
          })

          console.log('申请函上传结果:', uploadRes)

          // 期望后端返回 { code:1, data: { url: 'xxx' } }
          if (uploadRes && uploadRes.code === 1) {
            const url = uploadRes.data?.fullurl
            formData.apply = url
            uni.showToast({ title: '上传成功', icon: 'success' })
          } else {
            uni.showToast({ title: uploadRes.msg || '上传失败', icon: 'none' })
          }
        } catch (err) {
          console.error('申请函上传失败:', err)
          uni.showToast({ title: '上传失败', icon: 'none' })
        } finally {
          uni.hideLoading()
        }
      }
    })
  }

  // 省市区选择处理
  const onAreaChange = (areaData) => {
    if (!areaData) return
    console.log('城市选择结果:', areaData)

    // 显示文本
    formData.city = areaData.areaText
    // 后端所需的 id
    formData.province_id = areaData.province_id
    formData.city_id = areaData.city_id
    formData.region_id = areaData.region_id

    // 验证数据完整性
    if (formData.province_id && formData.city_id && formData.region_id) {
      console.log('城市选择完成:', {
        city: formData.city,
        province_id: formData.province_id,
        city_id: formData.city_id,
        region_id: formData.region_id
      })
    }
  }

  const onAreaCancel = () => {
    console.log('地区选择取消')
    // 可以选择是否重置已选择的值
    // resetAreaSelection()
  }

  // 下载申请函
  const downloadApplication = () => {
    uni.showToast({
      title: '下载功能开发中',
      icon: 'none'
    })
  }

  // 提交表单
  const submitForm = async () => {
    // 详细验证
    if (!formData.logo) {
      uni.showToast({ title: '请上传俱乐部logo', icon: 'none' })
      return
    }
    if (!formData.name) {
      uni.showToast({ title: '请输入俱乐部名称', icon: 'none' })
      return
    }
    if (!formData.contacts_name) {
      uni.showToast({ title: '请输入联系人', icon: 'none' })
      return
    }
    if (!formData.contacts_mobile) {
      uni.showToast({ title: '请输入联系电话', icon: 'none' })
      return
    }
    // 城市选择验证
    if (!formData.city || !formData.province_id || !formData.city_id || !formData.region_id) {
      uni.showToast({ title: '请选择完整的省市区信息', icon: 'none' })
      return
    }

    uni.showLoading({
      title: '提交中...'
    })

    // 调用真实API
    try {
      const params = {
        logo: formData.logo,
        name: formData.name,
        contacts_name: formData.contacts_name,
        contacts_mobile: formData.contacts_mobile,
        address: formData.address,
        creator_name: formData.creator_name,
        leader_name: formData.leader_name,
        license: formData.license,
        business: formData.business,
        apply: formData.apply,
        desc: formData.desc,
        province_id: formData.province_id,
        city_id: formData.city_id,
        region_id: formData.region_id
      }

      const result = await API_MEMBER_ADDCLUB_POST(params)

      if (result && result.code === 1) {
        uni.hideLoading()
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })

        // 返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } else {
        uni.hideLoading()
        throw new Error(result?.msg || '提交失败')
      }
    } catch (error) {
      uni.hideLoading()
      uni.showToast({
        title: error.msg || '提交失败，请重试',
        icon: 'none'
      })
    }
  }
  // 城市选择相关方法
  const areaPickerRef = ref(null)

  // 重置城市选择
  const resetAreaSelection = () => {
    if (areaPickerRef.value) {
      areaPickerRef.value.reset()
    }
    formData.city = ''
    formData.province_id = ''
    formData.city_id = ''
    formData.region_id = ''
  }

  // 设置城市选择（如果需要从其他地方设置）
  const setAreaSelection = async (provinceId, cityId, districtId) => {
    if (areaPickerRef.value) {
      await areaPickerRef.value.setValue(provinceId, cityId, districtId)
    }
  }
  onShow(() => {
    // 获取用户信息
    const storedUserInfo = uni.getStorageSync('userInfo')
    console.log('存储的用户信息:', storedUserInfo)

    if (storedUserInfo) {
      userInfo.value.nickname = storedUserInfo.nickname || storedUserInfo.username || ''
      userInfo.value.username = storedUserInfo.username || storedUserInfo.nickname || ''
    }

    // 设置创建者名称
    formData.creator_name = userInfo.value.nickname || userInfo.value.username || '李思雨'

    console.log('设置后的用户信息:', {
      nickname: userInfo.value.nickname,
      username: userInfo.value.username,
      creator_name: formData.creator_name
    })
  })
</script>

<style lang="scss" scoped>
  .form-container {
    padding: 24rpx;
    background: #fff;
    margin: 24rpx;
    border-radius: 16rpx;
  }

  .form-item {
    margin-bottom: 32rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .form-label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 12rpx;
    font-weight: 500;
  }

  .required {
    color: #ff4757;
  }

  .form-hint {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 16rpx;
  }

  .form-input {
    width: 100%;
    height: 80rpx;
    border: 2rpx solid #e8e8e8;
    border-radius: 8rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    background: #fff;
    box-sizing: border-box;

    &:focus {
      border-color: #213165;
    }
  }

  .form-textarea {
    width: 100%;
    min-height: 120rpx;
    border: 2rpx solid #e8e8e8;
    border-radius: 8rpx;
    padding: 24rpx;
    font-size: 28rpx;
    background: #fff;
    box-sizing: border-box;
    line-height: 1.5;

    &:focus {
      border-color: #213165;
    }
  }

  .form-readonly {
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 24rpx;
    background: #f8f9fa;
    border: 2rpx solid #e8e8e8;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #666;
  }

  .upload-box {
    width: 100%;
    height: 200rpx;
    border: 2rpx dashed #d9d9d9;

    .uploaded-image {
      width: 100%;
      height: 100%;
      border-radius: 8rpx;
    }

    .upload-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;

      .upload-icon {
        width: 64rpx;
        height: 64rpx;
        margin-bottom: 16rpx;
      }

      .upload-text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }

  .selected-city-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 16rpx;
    padding: 16rpx 24rpx;
    background: #f8f9fa;
    border-radius: 8rpx;

    .city-text {
      font-size: 28rpx;
      color: #333;
    }

    .city-reset {
      font-size: 24rpx;
      color: #213165;
      text-decoration: underline;
      cursor: pointer;
    }
  }

  .download-section {
    margin-bottom: 16rpx;
  }

  .download-link {
    color: #213165;
    font-size: 28rpx;
    text-decoration: underline;
  }

  .submit-section {
    padding: 24rpx;
    background: #fff;
    margin: 24rpx;
    border-radius: 16rpx;
  }

  .submit-btn {
    width: 100%;
    height: 88rpx;
    background: #213165;
    color: #fff;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: 500;

    &:disabled {
      background: #ccc;
      color: #999;
    }
  }
</style>
